package com.lyz.myself.controller;

import com.github.pagehelper.PageInfo;
import com.lyz.myself.config.utils.JwtUtil;
import com.lyz.myself.config.utils.Result;
import com.lyz.myself.config.utils.base.CodeMsg;
import com.lyz.myself.config.utils.util.DateUtil;
import com.lyz.myself.config.utils.util.JsonUtil;
import com.lyz.myself.config.utils.util.JsonXMLUtils;
import com.lyz.myself.config.utils.util.LogUtils;
import com.lyz.myself.pojo.Po.Contacts;
import com.lyz.myself.pojo.Po.Customer;
import com.lyz.myself.service.ContactsService;
import com.lyz.myself.service.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: myself
 * @Date: 2019/1/10 16:58
 * @Author: Mr.Deng
 * @Description:
 */
@Api(description = "客户模块")
@RestController
@RequestMapping("/ordinaryCustomer")
public class OrdinaryCustomerContoller extends BaseController {
    public final static Logger logger = LoggerFactory.getLogger(OrdinaryCustomerContoller.class);
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ContactsService contactsService;

    @ApiOperation("所有客户（手机号和姓名）")
    @RequiresAuthentication
    @RequestMapping(path = "/getAllCustomer", method = RequestMethod.GET)
    public Result getAllCustomer(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        Integer creator_role_id = JwtUtil.getUserId();
        int company_id = getUser().getCompany_id();
        PageInfo<Map<String, String>> pageInfo = customerService.getAllCustomer(creator_role_id, company_id, pageNum, pageSize);
        if (pageInfo.getSize() > 0) {
            return Result.success(pageInfo, "查询成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "暂无信息！");
        }
    }

    @ApiOperation("查询普通用户下客户订单（客户池）")
    @RequiresAuthentication
    @RequestMapping(value = "/selectGeneralCustomer", method = RequestMethod.GET)
    public Result selectGeneralCustomer(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        System.out.println(pageNum + "   " + pageSize);
        PageInfo<Map<String, String>> pageInfo = customerService.selectGeneralCustomer(pageNum, pageSize);
        return Result.success(pageInfo, "查询成功！");
    }

    @ApiOperation("我的客户（ 全部 ）")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/selectCustomer", method = RequestMethod.GET)
    public Result selectCustomer(String filter, String contains, String search, String focus, Integer create_time, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        Integer user_id = 0;
        if (focus != null) {
            user_id = JwtUtil.getUserId();
        }
        //今日，本周，本月创建
        Integer times_night = 0;
        Integer times_morning = 0;
        if (create_time != null && create_time == 1) {
            times_night = DateUtil.getTimesnight();
            times_morning = DateUtil.getTimesmorning();
        } else if (create_time != null && create_time == 7) {
            times_night = DateUtil.getTimesWeeknight();
            times_morning = DateUtil.getTimesWeekmorning();
        } else if (create_time != null && create_time == 30) {
            times_night = DateUtil.getTimesnight();
            times_morning = DateUtil.getTimesMonthmorning();
        }
        Integer userId = JwtUtil.getUserId();
        Integer creator_role_id = userId;
        int company_id = getUser().getCompany_id();
        //0创建时间,1修改时间，2客户联系地址,3邮编，4服务类型,5客户名称（filter）
        //(contains)0包含,1不包含,2是，3不是，4开始字符，5结束字符，6为空，7不为空,8教育/培训,9电子商务,10对外贸易,11电话营销,12网络营销
        //13老客户转介绍,14阿里巴巴,15百度,16合资,17国企,18民营
        if (filter != null) {
            if (filter.equals("创建时间") || filter.equals("修改时间") || filter.equals("客户联系地址") || filter.equals("邮编") || filter.equals("服务类型") || filter.equals("客户名称")) {
                contains = contains + "呀";
            }
        }
        Map<String,Object> mapInsert = new HashMap<>();
        mapInsert.put("filter",filter);
        mapInsert.put("contains",contains);
        mapInsert.put("search",search);
        mapInsert.put("create_time",create_time);
        mapInsert.put("times_night",times_night);
        mapInsert.put("times_morning",times_morning);
        mapInsert.put("user_id",user_id);
        mapInsert.put("company_id",company_id);
        mapInsert.put("creator_role_id",creator_role_id);
        mapInsert.put("pageNum",pageNum);
        mapInsert.put("pageSize",pageSize);
        PageInfo<Map<String, String>> pageInfo = customerService.selectCustomer(mapInsert);
        if (pageInfo.getSize() > 0) {
            return Result.success(pageInfo, "查询成功！");
        } else {
            return Result.error(CodeMsg.ERROR, "暂无数据！");
        }
    }


    @ApiOperation("根据id 删除指定客户")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/deleteCustomer", method = RequestMethod.POST)
    public Result deleteCustomer(String customer_id, Integer company_id) {
        if (customer_id != null) {
            List<Integer> list = new ArrayList<Integer>();
            String[] str = customer_id.split(",");
            for (int i = 0; i < str.length; i++) {
                list.add(Integer.parseInt(str[i]));
            }
            Integer creator_role_id = JwtUtil.getUserId();//获取当前登陆人id
            Integer thisData = DateUtil.timeMillis();//取得当前时间戳（精确到秒10位）
            int deleteCustomer = customerService.deleteCustomer(creator_role_id, company_id, thisData, list);
            if (deleteCustomer > 0) {
                return Result.success(deleteCustomer, "删除成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "删除失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请选择要删除的客户");
        }

    }

    @ApiOperation("添加客户")
    @RequiresAuthentication//登陆状态  1
    @RequestMapping(value = "/insertCustomer", method = RequestMethod.POST)
    public Result insertCustomer(@RequestBody Params param) throws Exception {
        //Customer customer= JsonXMLUtils.map2obj((Map<String, Object>)models.get("customer"),Customer.class);
        //Contacts contacts=JsonXMLUtils.map2obj((Map<String,Object>)models.get("contacts"),Contacts.class);
        Customer customer = param.getCustomer();
        Contacts contacts = param.getContacts();
        if (customer != null && contacts != null) {
            if(customer.getAddress()==null){
                customer.setAddress("");
            }
            if(customer.getAnnual_revenue()==null){
                customer.setAnnual_revenue("");
            }
            if(customer.getCrm_tkygmd()==null){
                customer.setCrm_tkygmd("");
            }
            if(customer.getIndustry()==null){
                customer.setIndustry("");
            }
            if(customer.getIs_sms()==null){
                customer.setIs_sms(1);
            }
            if(customer.getAddress()==null){
                customer.setAddress("");
            }
            if(customer.getName()==null){
                customer.setName("");
            }
            if(customer.getNo_of_employees()==null){
                customer.setNo_of_employees(0);
            }
            if(customer.getOrigin()==null){
                customer.setOrigin("");
            }
            if(customer.getOwnership()==null){
                customer.setOwnership("");
            }
            if(customer.getRating()==null){
                customer.setRating("");
            }
            if(customer.getSms_count()==null){
                customer.setSms_count("");
            }
            if(customer.getZip_code()==null){
                customer.setZip_code("");
            }
                customer.setCreator_role_id(getUser().getUser_id());
            int company_id = getUser().getCompany_id();
            Integer thisData = DateUtil.timeMillis();//取得当前时间戳（精确到秒10位）
            if(customer.getRating()==null){
                customer.setRating("");
            }
            if(contacts.getDescription()==null){
                contacts.setDescription("");
            }
            if(contacts.getEmail()==null){
                contacts.setEmail("");
            }
            if(contacts.getName()==null){
                contacts.setName("");
            }
            if(contacts.getPost()==null){
                contacts.setPost("");
            }
            if(contacts.getQq_no()==null){
                contacts.setQq_no("");
            }
            if(contacts.getSaltname()==null){
                contacts.setSaltname("");
            }
            if(contacts.getTelephone()==null){
                contacts.setTelephone("");
            }
            contacts.setCreate_time(thisData);
            contacts.setIs_deleted(0);
            contacts.setDepartment("");
            contacts.setSex(0);
            contacts.setAddress("");
            contacts.setZip_code("");
            contacts.setDelete_role_id(0);
            contacts.setDelete_time(0);
            contacts.setCreator_role_id(customer.getCreator_role_id());
            contacts.setUpdate_time(thisData);
            contacts.setCompany_id(company_id);
            int insertContacts = contactsService.insertContacts(contacts);

            customer.setContacts_id(contacts.getContacts_id());
            customer.setCreate_time(thisData);
            customer.setCompany_id(company_id);
            customer.setUpdate_time(thisData);
            customer.setIs_deleted(0);
            customer.setIs_locked(0);
            customer.setIs_show(1);
            customer.setDelete_role_id(0);
            customer.setDelete_time(0);
            customer.setOwner_role_id(getUser().getRole_id());
            if (customer.getIs_sms() != 1) {
                customer.setSms_count(" ");
            }
            int customer_id = customerService.insertCustomer(customer);

            if (customer_id > 0 && insertContacts > 0) {
                return Result.success(customer_id, "添加成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "添加失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要添加的信息！");
        }
    }

    @ApiOperation("修改客户信息")
    @RequiresAuthentication//登陆状态1
    @RequestMapping(value = "/upadteCustomer", method = RequestMethod.POST)
    public Result upadteCustomer(@RequestBody Params param) throws Exception {
       /* Customer customer= JsonXMLUtils.map2obj((Map<String, Object>)models.get("customer"),Customer.class);
        Contacts contacts=JsonXMLUtils.map2obj((Map<String,Object>)models.get("contacts"),Contacts.class);*/
        Customer customer = param.getCustomer();
        Contacts contacts = param.getContacts();
        if (param != null) {
             customer.setCreator_role_id(getUser().getRole_id());
            Integer thisData = DateUtil.timeMillis();//取得当前时间戳（精确到秒10位）
            customer.setUpdate_time(thisData);
            contacts.setUpdate_time(thisData);
            contacts.setCompany_id(getUser().getCompany_id());
            int upadteContacts = contactsService.upadteContacts(contacts);
            int insertCustomer = customerService.upadteCustomer(customer);
            if (insertCustomer > 0||upadteContacts > 0) {
                return Result.success(insertCustomer, "修改成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "修改失败！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要修改的信息！");
        }
    }

    /**
     *
     */
    @ApiOperation("根据id查看客户信息")
    @RequiresAuthentication//登陆状态
    @RequestMapping(value = "/getCustomer", method = RequestMethod.POST)
    public Result getCustomer(Integer customer_id) {
        if (customer_id != null) {
            int company_id = getUser().getCompany_id();
            Map<String, String> map = customerService.getCustomer(customer_id, company_id);
            if (map != null && map.size() > 0) {
                return Result.success(map, "查询成功！");
            } else {
                return Result.error(CodeMsg.ERROR, "暂无数据！");
            }
        } else {
            return Result.error(CodeMsg.ERROR, "请输入要查看的客户的id！");
        }
    }

}

class Params {
    private Customer customer;
    private Contacts contacts;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Contacts getContacts() {
        return contacts;
    }

    public void setContacts(Contacts contacts) {
        this.contacts = contacts;
    }
}
